// pages/upload/index.js
import {request} from '../../request/index.js'
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';
var amapFile = require('../../lib/amap-wx');
var myAmapFun;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    DisForm:{
      "city": "",
      "date": "",
      "filename": "",
      "latitude": "",
      "longitude": "",
      "number": "",
      "picture_Id": "",
      "road": "",
      "square": "",
      "status": 0,
      "type": "",
    },
    showCity:false, // 展示所有地区
    showType:false, // 展示所有类型
    CityForm:[],
    TypeForm:[],
    showDate:false, //展示选择月份
    currentDate: new Date().getTime(),
    // minDate: new Date().getTime(),
    Date:'',
    nowCity:"请选择病害所处地区",
    nowType:"请选择病害类型",
    fileList:[],
    imgfileList:[],
    posName: '点击进行定位选择',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getAllCity();
    this.getAllType();
    this.setData({
      "DisForm[0].status":0,
      "DisForm[0].filename":"",
      "DisForm[0].picture_Id": "",
    })
  },

   // 选择地区
   async getAllCity(){
    const res = await request({
      url: '/newDiseases/getAllCities',
      method: "get",
    })
    // console.log(res)
    if (res.errCode !== 200){
      var title = res.errMsg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
    }
    else {
      let arr = []
      let that = this
      let cityList = res.data
      cityList.forEach(function(item){
        arr.push(item.city)
      })
      that.setData({
        CityForm : arr
      })
      // console.log(that.data.CityForm)
    }
  },
   // 选择类型
   async getAllType(){
    const res = await request({
      url: '/newDiseases/getAllType',
      method: "get",
    })
    // console.log(res)
    if (res.errCode !== 200){
      var title = res.errMsg
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000
      })
    }
    else {
      let arr = []
      let that = this
      let TypeList = res.data
      TypeList.forEach(function(item){
        arr.push(item.type)
      })
      that.setData({
        TypeForm : arr
      })
      // console.log(that.data.TypeForm)
    }
  },
  // 获取面积
  onChangeSquare(event){
    this.setData({
      "DisForm[0].square":event.detail
    });
  },
  // 获取数量
  onChangeNum(event){
    this.setData({
      "DisForm[0].number":event.detail
    });
  },
  // 获取道路
  onChangeRoad(event){
    this.setData({
      "DisForm[0].road":event.detail
    });
  },
  chooseCity(){
    this.setData({
      showCity: true
    })
  },
  chooseType(){
    this.setData({
      showType: true
    })
  },
   // 日期转换
   toChangeTime(time){
    let year = time.getFullYear()
    let month = time.getMonth() + 1
    let months = ''
    if (month < 10) { months = '0' + month }
    this.setData({
      "DisForm[0].date":year+''+months,
      Date: year +'年' + month +  '月'
    });
   },
  onCityClose(){
    this.setData({
      showCity: false
    })
  },
  onCitySelect(event){
    this.setData({
      nowCity: event.detail.value,
      "DisForm[0].city":event.detail.value
    })
    this.onCityClose()
  },
  onTypeClose(){
    this.setData({
      showType: false
    })
  },
  onTypeSelect(event){
    this.setData({
      nowType: event.detail.value,
      "DisForm[0].type":event.detail.value
    })
    this.onTypeClose()
  },

  // 选择日期
  chooseDate(){
    this.setData({
      showDate: true
    })
  },
  onDateClose()
  {
    this.setData({
      showDate: false
    })
  },
  onDateSelect(event) {
    let time = new Date(event.detail)
    this.toChangeTime(time)
    this.onDateClose()
  },
  onDateSelect1(event) {
    let time = new Date(event.detail)
    this.toChangeTime(time)
  },
// 文件上传完毕回调函数after-read
afterReadImg(event) {
  const { file } = event.detail; // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  this.setData({
      imgfileList:[...this.data.imgfileList, ...file]
  })
  // this.uploadImg(file);
},

  // 删除文件
  deleteImg(event) {
    // console.log(event)
    let imgDelIndex = event.detail.index
    let fileList = this.data.imgfileList
    fileList.splice(imgDelIndex,1)
    // console.log('删除图片的',fileList)
    this.setData({
        imgfileList : fileList
    })
    // this.uploadImg(fileList)
  },
  // 文件上传完毕回调函数after-read
  afterRead(event) {
    const { file } = event.detail; // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    this.setData({
        fileList:[...this.data.fileList, ...file]
    })
    // this.uploadImg(file);
},

// 删除文件
delete(event) {
    // console.log(event)
    let DelIndex = event.detail.index
    let fileList = this.data.fileList
    fileList.splice(DelIndex,1)
    this.setData({
        fileList:fileList
    })
},
// 获取定位权限
handleGetPos(){
  //  let that = this
  //   wx.chooseLocation({
  //     success:function(res){
  //       // console.log(res)
  //       that.setData({
  //         posName: res.address,
  //         "DisForm[0].latitude": res.latitude,
  //         "DisForm[0].longitude": res.longitude
  //       })
  //       // console.log(res.address)
  //     }
  //   })

  myAmapFun = new amapFile.AMapWX({key: '4e0a28c614e26768147e26d1945e842f'})
    let that = this
    myAmapFun.getRegeo({
      success:(res)=>{
        console.log(res)
        that.setData({
          posName: res[0].name,
          "DisForm[0].latitude": res[0].latitude,
          "DisForm[0].longitude": res[0].longitude
        })
      }
    })
   
  },
// 上传图片
  async uploadImg(){
    console.log(this.data.imgfileList)
    if(this.data.imgfileList[0]){
      let that  = this
      for (var i in that.data.imgfileList) {
        wx.uploadFile({
          url: 'http://47.93.241.187:8000/Upload/picture', 
          filePath: that.data.imgfileList[i].url,
          name: 'file',
          success (ress){
            let str = ress.data
            let res  = JSON.parse(str.replace(/\'/g,'\"').substring(str.indexOf("{"),str.indexOf("}")+1))
            console.log(res)
            if (res.errCode !== 200){
              var title = res.errMsg
              wx.showToast({
                title: title,
                icon: 'none',
                duration: 2000
              })
            }
            else {
              that.setData({
                "DisForm[0].picture_Id":res.data
              }, () => {
                that.uploadFile()
              })
            }
          }
        })
      }
    }
    else {
      this.uploadFile()
    }
  },
  // 上传文件
  async uploadFile(){
    console.log(this.data.imgfileList)
    if(this.data.imgfileList[0]){
      let that = this
      for (var i in that.data.imgfileList) {
        wx.uploadFile({
          url: 'http://47.93.241.187:8000/Upload/picture', 
          filePath: that.data.imgfileList[i].url,
          name: 'file',
          success (ress){
            let str = ress.data
            let res  = JSON.parse(str.replace(/\'/g,'\"').substring(str.indexOf("{"),str.indexOf("}")+1))
            console.log(res)
            if (res.errCode !== 200){
              var title = res.errMsg
              wx.showToast({
                title: title,
                icon: 'none',
                duration: 2000
              })
            }
            else {
              that.setData({
                "DisForm[0].filename":res.data
              },()=>{
                that.uploadAll()
              })
            }
          }
        })
      }
    }
    else {
      this.uploadAll()
    }
  },
  // 提交
  async uploadAll(){
    console.log(this.data.DisForm[0])
    let arr = this.data.DisForm[0]
    if(this.data.DisForm[0].city && this.data.DisForm[0].latitude && this.data.DisForm[0].longitude && this.data.DisForm[0].date && this.data.DisForm[0].number && this.data.DisForm[0].square && this.data.DisForm[0].type){
        const res = await request({
          url: '/newDiseases/InsertDiseases',
          data: arr,
          method: "post",
        })
        console.log(res)
        if (res.errCode !== 200){
          if(res.data){
            wx.showToast({
              title: res.data,
              icon: 'none',
              duration: 2000
            })
          }
          else{
             var title = res.errMsg
             wx.showToast({
              title: title,
              icon: 'none',
              duration: 2000
            })
          }
          setTimeout(function(){
            wx.redirectTo({
              url: '/pages/info/fail/index',
            })
          },1500)
        }
        else {
          wx.showToast({
            title: '上传成功',
            icon: 'success',
            duration: 1500
          })
          setTimeout(function(){
            wx.redirectTo({
              url: '/pages/info/success/index',
            })
          },1500)
        }
    }
    else {
      wx.showToast({
        title: '请填写完整表单信息',
        icon: 'error',
        duration: 1500
      })
    }
   
  },
    

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})